package com.globallogic.week3.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.globallogic.week3.util.AuthUserHandler;
import com.globallogic.week3.util.MD5Util;
import com.globallogic.week3.util.UserHandler;

@WebServlet(urlPatterns="/login")
public class LoginServlet extends HttpServlet{
	
	private static final Logger log = Logger.getLogger(LoginServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		req.getRequestDispatcher("login.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String login = req.getParameter("login");
		String password = req.getParameter("password");
		
		//TODO validation on null
		
		
		UserHandler handler = (UserHandler) req.getServletContext().getAttribute("handler");
		AuthUserHandler authUserHandler = (AuthUserHandler) req.getServletContext().getAttribute("authUserHandler");
		
		
		if(handler.containsLogin(login)){
			String retrievedPass = handler.getPass(login);
			
			if(retrievedPass.equals(MD5Util.encode(password))){
				String sesionId = req.getSession().getId();
				log.debug("Session  id: "+sesionId);
				req
					.getSession()
					.setAttribute("isAuth", sesionId);
				authUserHandler.add(sesionId);
				req.getRequestDispatcher("secured_page.jsp").forward(req, resp);
			}else{
				forwardToErrorPage(req, resp);
			}
		}else{
			forwardToErrorPage(req, resp);
		}
		
	}
	
	private void forwardToErrorPage(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		req.setAttribute("operationStatus", "The username or password is incorrect!");
		req.getRequestDispatcher("notify.jsp").forward(req, resp);
	}
	

}
